package com.test.demo.aspect;

import com.test.demo.annotation.SecuityAuth;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 权限检验切面
 *
 * @author hzx
 */
@Aspect//声明这是一个切面
@Component
public class SecurityAspect {

    @Pointcut("@within(com.test.demo.annotation.MyLog) || @annotation(com.test.demo.annotation.MyLog)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public void doBefore(ProceedingJoinPoint joinPoint) {
        //拿到响应
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        //拿到请求
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //请求头中获取用户token
        String tokenHeader = request.getHeader("userToken");
        //从切面织入点通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //获取方法上的注解
        SecuityAuth annotation = method.getAnnotation(SecuityAuth.class);
        String methodRoleName = annotation.roleName();
        //todo  用户token中的role信息和方法上的role是否匹配，
        //      如果匹配，进去方法，不匹配则调用 returnErrorResponse() 错误信息
        try {
            //权限不够，返回响应体
            if (tokenHeader != methodRoleName) {
                returnErrorResponse(response);
            }
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }



    public void returnErrorResponse(HttpServletResponse response) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print("");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }

    }

}
